package com.nwpu.intimacy.main;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sun.misc.BASE64Decoder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.about.AboutActivity;
import com.nwpu.intimacy.adapter.FriendMessageAdapter;
import com.nwpu.intimacy.adapter.MessageAdapter;
import com.nwpu.intimacy.adapter.PinyinAdapter;
import com.nwpu.intimacy.baidumapsdk.LocationDemo;
import com.nwpu.intimacy.been.ChatFriendInformation;
import com.nwpu.intimacy.been.FriendInformation;
import com.nwpu.intimacy.chat.ChatActivity;
import com.nwpu.intimacy.chat.ListData;
import com.nwpu.intimacy.friend.AddFriendRequestActivity;
import com.nwpu.intimacy.friend.FriendInformationActivity;
import com.nwpu.intimacy.keword.KeywordActivity;
import com.nwpu.intimacy.login.LoginActivity;
import com.nwpu.intimacy.myView.MyPinyinSideBar;
import com.nwpu.intimacy.myView.MyPinyinSideBar.OnTouchAssortListener;
import com.nwpu.intimacy.scan.MipcaActivityCapture;
import com.nwpu.intimacy.shake.ShakeActivity;
import com.nwpu.intimacy.user.UserInformationActivity;
import com.nwpu.intimacy.utils.CacheUtil;
import com.nwpu.intimacy.utils.ReceiveThread;
import com.nwpu.intimacy.utils.SelectAddPopupWindow;

public class MainActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/addUser";

	private static final String IP_SOCKET = "10.128.51.203";
	private static final int PORT_SOCKET = 9000;

	private final static int USER_ADD_SUCCESS = 0x114;
	private final static int USER_ADD_MESSAGE = 0x115;

	private final static int FRIENDMESSAGE_ONTIME = 0x116;
	private final static int FRIENDMESSAGE_OFFLINE = 0x117;

	private List<FriendInformation> friendInformations;
	private List<String> friendList;

	private PinyinAdapter adapter;
	private ExpandableListView eListView;
	private MyPinyinSideBar assortView;

	private SharedPreferences sp_userMessage;

	private ListView list_friend;
	private List<ChatFriendInformation> chatFriendInformations;
	private FriendMessageAdapter adapter_FriendMessage;

	private Button menu_linearlayout0;
	private Button menu_linearlayout1;
	private Button menu_linearlayout2;
	private Button menu_linearlayout3;

	private ImageView menu_action_intimacy;
	private ImageView menu_action_addressBook;
	private ImageView menu_action_findFriends;
	private ImageView menu_action_myInfromation;

	private TextView txt_intimacy;
	private TextView txt_addressBook;
	private TextView txt_findFriends;
	private TextView txt_myInfromation;

	public static ViewPager mViewPager;
	private List<View> views;
	private View view1, view2, view3, view4;
	private int setPosition = 0;

	private long firstTime = 0;

	private LinearLayout linearLayout;
	private ImageView head_item;
	private TextView item_name;

	private LinearLayout view4_linearLayout;
	private TextView view4_user_name_my;
	private ImageView view4_user_image_my;
	private Button exit_account_button;
	private Button about_us_button;

	private ImageView shake_findFriend;
	private ImageView scan_findFriend;
	private ImageView nearby_findFriend;

	private TextView unread_msg_number;
	private TextView unread_address_number;

	private int address_number = 0;

	private ImageView actionbar_add;
	private ImageView actionbar_search;

	private Handler mHandler;
	private Handler addHandler;
	private Handler friendHandler;

	static final int REQUEST_CODE = 10000;
	static final int REQUEST_CODE_2 = 20000;

	private static String socketMessage;

	// 自定义的弹出框类
	SelectAddPopupWindow menuWindow; // 弹出框

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		chatFriendInformations = new ArrayList<ChatFriendInformation>();
		sendSocketMessage();
		getUserMessageAlsways();

		getActionBar().hide();

		setPosition = getIntent().getIntExtra("setPosition", 0);

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		friendInformations = new ArrayList<FriendInformation>();
		friendList = new ArrayList<String>();

		initFriendsList();
		initLayout();
		initViewPager();

		unread_msg_number.setVisibility(View.GONE);
		unread_address_number.setVisibility(View.GONE);

		actionbar_search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), KeywordActivity.class);
				startActivity(intent);

			}
		});

		actionbar_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				uploadImage(MainActivity.this);

			}
		});

		mHandler = new Handler();
		mHandler.post(new Runnable() {
			@Override
			public void run() {

				getFriendRequest();
				mHandler.postDelayed(this, 5000);
			}
		});

		addHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_ADD_MESSAGE: {
					// 跳转界面 登录成功

					try {

						address_number = address_number + 1;

						unread_address_number.setVisibility(View.VISIBLE);
						unread_address_number.setText(address_number + "");

						String str = CacheUtil.getFromFile(
								sp_userMessage.getString("USER_NAME", "")
										+ "requestFriend", "Request");
						if (str.equals("[]") || str.equals("")) {

							CacheUtil.writeToFile(msg.obj.toString(),
									sp_userMessage.getString("USER_NAME", "")
											+ "requestFriend", "Request");

						} else {

							JSONArray jsonArray_file = new JSONArray(str);
							JSONArray jsonArray_msg = new JSONArray(
									msg.obj.toString());
							JSONObject jsonObject = (JSONObject) jsonArray_msg
									.get(0);

							JSONArray jsonArray_new = new JSONArray();

							for (int i = 0; i < jsonArray_file.length(); i++) {

								JSONObject jsonObject2 = (JSONObject) jsonArray_file
										.get(i);
								if (jsonObject2.optString("username").equals(
										jsonObject.optString("username"))) {

									jsonArray_new.put(jsonObject);

								} else {

									jsonArray_new.put(jsonObject2);

								}

							}

							Log.e("woshishishsis", jsonArray_new.toString());

							CacheUtil.writeToFile(jsonArray_new.toString(),
									sp_userMessage.getString("USER_NAME", "")
											+ "requestFriend", "Request");

						}

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				case USER_ADD_SUCCESS: {
					// 跳转界面 登录成功

					try {

						String friend_str = CacheUtil.getFromFile(
								"friendsInformation", "Friend");

						JSONArray jsonArray_friend = new JSONArray(friend_str);
						JSONObject jsonObject_friend = new JSONObject();
						JSONObject jsonObject_msg = new JSONObject(
								msg.obj.toString());

						jsonObject_friend.put("username",
								jsonObject_msg.optString("username"));
						jsonObject_friend.put("area",
								jsonObject_msg.optString("area"));
						jsonObject_friend.put("signature",
								jsonObject_msg.optString("signature"));
						jsonObject_friend.put("sex",
								jsonObject_msg.optString("sex"));

						jsonArray_friend.put(jsonObject_friend);

						CacheUtil.WriteToFile(jsonObject_msg.opt("username")
								.toString(), stringtoBitmap(jsonObject_msg
								.optString("portrait")), "FriendPhoto");

						CacheUtil.writeToFile(jsonArray_friend.toString(),
								"friendsInformation", "Friend");

						// eListView.clearChoices();
						// eListView.clearAnimation();
						// adapter.clear();
						// adapter.notifyDataSetChanged();
						// eListView.setAdapter(adapter);

						break;

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				default:
					super.handleMessage(msg);
				}
			}

		};

		friendHandler = new Handler() {

			@SuppressLint("NewApi")
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {

				case FRIENDMESSAGE_ONTIME:

					try {

						JSONArray jsonArray = new JSONArray(msg.obj.toString());
						JSONObject jsonObject;

						ChatFriendInformation chatFriendInformation = null;

						for (int i = 0; i < jsonArray.length(); i++) {

							jsonObject = (JSONObject) jsonArray.get(i);

							storeToFile(jsonObject);

							if (jsonObject.optInt("type") == 1) {

								chatFriendInformation = new ChatFriendInformation(
										CacheUtil.GetFromFile(
												jsonObject.optString("sendid"),
												"FriendPhoto"),
										jsonObject.optString("sendid"),
										jsonObject.optString("message"),
										getTime(jsonObject.optLong("time")));

							} else if (jsonObject.optInt("type") == 2) {

								chatFriendInformation = new ChatFriendInformation(
										CacheUtil.GetFromFile(
												jsonObject.optString("sendid"),
												"FriendPhoto"),
										jsonObject.optString("sendid"),
										"Photo",
										getTime(jsonObject.optLong("time")));

							} else if (jsonObject.optInt("type") == 3) {

								chatFriendInformation = new ChatFriendInformation(
										CacheUtil.GetFromFile(
												jsonObject.optString("sendid"),
												"FriendPhoto"),
										jsonObject.optString("sendid"),
										"Voice",
										getTime(jsonObject.optLong("time")));

							} else if (jsonObject.optInt("type") == 4) {

								chatFriendInformation = new ChatFriendInformation(
										CacheUtil.GetFromFile(
												jsonObject.optString("sendid"),
												"FriendPhoto"),
										jsonObject.optString("sendid"), "File",
										getTime(jsonObject.optLong("time")));

							}

							ChatFriendInformation chatFriendInformation_new;

							if (chatFriendInformations.isEmpty()) {

								chatFriendInformations
										.add(chatFriendInformation);
								adapter_FriendMessage.notifyDataSetChanged();

							}

							for (int j = 0; j < chatFriendInformations.size(); j++) {

								chatFriendInformation_new = chatFriendInformations
										.get(j);

								if (jsonObject.optString("sendid")
										.equals(chatFriendInformation_new
												.getUsername())) {

									chatFriendInformations.remove(i);

									chatFriendInformations
											.add(chatFriendInformation);
									adapter_FriendMessage
											.notifyDataSetChanged();

								}

							}

						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;

				case FRIENDMESSAGE_OFFLINE:

					break;

				default:
					super.handleMessage(msg);
				}
			}
		};

	}

	protected void onActivityResult(int requestcode, int resultCode, Intent data) {

		// 在这里进行关闭

		switch (requestcode) {

		case REQUEST_CODE:
			finish();
			break;

		case REQUEST_CODE_2:
			finish();
			break;
		}

	}

	// 初始化控件
	private void initLayout() {

		menu_linearlayout0 = (Button) findViewById(R.id.menu_linearlayout0);
		menu_linearlayout1 = (Button) findViewById(R.id.menu_linearlayout1);
		menu_linearlayout2 = (Button) findViewById(R.id.menu_linearlayout2);
		menu_linearlayout3 = (Button) findViewById(R.id.menu_linearlayout3);

		menu_linearlayout0.setOnClickListener(new TabClickListener(0));
		menu_linearlayout1.setOnClickListener(new TabClickListener(1));
		menu_linearlayout2.setOnClickListener(new TabClickListener(2));
		menu_linearlayout3.setOnClickListener(new TabClickListener(3));

		menu_action_intimacy = (ImageView) findViewById(R.id.menu_action_intimacy);
		menu_action_addressBook = (ImageView) findViewById(R.id.menu_action_addressBook);
		menu_action_findFriends = (ImageView) findViewById(R.id.menu_action_findFriends);
		menu_action_myInfromation = (ImageView) findViewById(R.id.menu_action_myInfromation);

		txt_intimacy = (TextView) findViewById(R.id.txt_intimacy);
		txt_addressBook = (TextView) findViewById(R.id.txt_addressBook);
		txt_findFriends = (TextView) findViewById(R.id.txt_findFriends);
		txt_myInfromation = (TextView) findViewById(R.id.txt_myInfromation);

		actionbar_add = (ImageView) findViewById(R.id.actionbar_add);
		actionbar_search = (ImageView) findViewById(R.id.actionbar_search);

		unread_msg_number = (TextView) findViewById(R.id.unread_msg_number);
		unread_address_number = (TextView) findViewById(R.id.unread_address_number);

	}

	// 初始化ViewPager，并处理每一个view的点击事件
	private void initViewPager() {

		// 添加view
		mViewPager = (ViewPager) findViewById(R.id.main_pager);
		views = new ArrayList<View>();
		LayoutInflater inflater = getLayoutInflater();
		view1 = inflater.inflate(R.layout.activity_intimacy, null);
		view2 = inflater.inflate(R.layout.activity_addressbook, null);
		view3 = inflater.inflate(R.layout.activity_findpeople, null);
		view4 = inflater.inflate(R.layout.activity_myinformation, null);
		views.add(view1);
		views.add(view2);
		views.add(view3);
		views.add(view4);
		mViewPager.setAdapter(new MyViewPagerAdapter(views));
		mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
		mViewPager.setCurrentItem(setPosition);

		list_friend = (ListView) view1
				.findViewById(R.id.friendMessage_intimacy);

		adapter_FriendMessage = new FriendMessageAdapter(
				chatFriendInformations, this);
		list_friend.setAdapter(adapter_FriendMessage);

		list_friend.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				String username = ((TextView) view
						.findViewById(R.id.chat_friend_name)).getText()
						.toString();

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ChatActivity.class);
				intent.putExtra("friendname", username);
				startActivity(intent);

				try {

					CacheUtil.writeToFile(username, "UserChat", "Send/User");

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		head_item = (ImageView) view2.findViewById(R.id.head_user);
		head_item.setImageResource(R.drawable.a_1);

		item_name = (TextView) view2.findViewById(R.id.user_friend_name);
		item_name.setText("Recommended Friends");

		linearLayout = (LinearLayout) view2.findViewById(R.id.friend_new);
		linearLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(),
						AddFriendRequestActivity.class);
				startActivity(intent);

				address_number = 0;
				unread_address_number.setVisibility(View.GONE);

			}
		});

		eListView = (ExpandableListView) view2.findViewById(R.id.elist);
		assortView = (MyPinyinSideBar) view2.findViewById(R.id.assort);

		adapter = new PinyinAdapter(this, friendList);
		eListView.setAdapter(adapter);

		eListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {

				String username = ((TextView) v
						.findViewById(R.id.user_friend_name)).getText()
						.toString();

				for (int i = 0; i < friendInformations.size(); i++) {

					FriendInformation friendInformation = friendInformations
							.get(i);
					if (friendInformation.getUsername().equals(username)) {

						Intent intent = new Intent();

						FriendInformationActivity.initInformation(
								friendInformation.getUsername(),
								friendInformation.getSex() + "",
								friendInformation.getArea(), friendInformation
										.getSignature(), "Delete Friend",
								CacheUtil.GetFromFile(
										friendInformation.getUsername(),
										"FriendPhoto"));

						intent.setClass(getApplicationContext(),
								FriendInformationActivity.class);

						setResult(REQUEST_CODE_2, intent);

						// startActivityForResult(intent, REQUEST_CODE_2);
						startActivity(intent);

						i = friendInformations.size();

						return false;

					}

				}

				return false;
			}
		});

		// 展开所有
		for (int i = 0, length = adapter.getGroupCount(); i < length; i++) {
			eListView.expandGroup(i);
		}

		// 字母按键回调
		assortView.setOnTouchAssortListener(new OnTouchAssortListener() {

			View layoutView = LayoutInflater.from(MainActivity.this).inflate(
					R.layout.contactslist_alert_dialog_menu_layout, null);
			TextView text = (TextView) layoutView.findViewById(R.id.content);
			PopupWindow popupWindow;

			public void onTouchAssortListener(String str) {
				int index = adapter.getAssort().getHashList().indexOfKey(str);
				if (index != -1) {
					eListView.setSelectedGroup(index);

				}
				if (popupWindow != null) {
					text.setText(str);
				} else {
					popupWindow = new PopupWindow(layoutView, 80, 80, false);
					// 显示在Activity的根视图中心
					popupWindow.showAtLocation(getWindow().getDecorView(),
							Gravity.CENTER, 0, 0);
				}
				text.setText(str);
			}

			public void onTouchAssortUP() {
				if (popupWindow != null)
					popupWindow.dismiss();
				popupWindow = null;
			}
		});

		shake_findFriend = (ImageView) view3
				.findViewById(R.id.findFriend_shake);
		scan_findFriend = (ImageView) view3.findViewById(R.id.findFriend_scan);
		nearby_findFriend = (ImageView) view3
				.findViewById(R.id.findFriend_nearby);

		shake_findFriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ShakeActivity.class);
				startActivity(intent);

			}
		});

		scan_findFriend = (ImageView) view3.findViewById(R.id.findFriend_scan);
		scan_findFriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, MipcaActivityCapture.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);

			}
		});

		nearby_findFriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), LocationDemo.class);
				startActivity(intent);

			}
		});

		view4_user_image_my = (ImageView) view4
				.findViewById(R.id.user_image_my);
		Bitmap photo = CacheUtil.GetFromFile(
				sp_userMessage.getString("USER_NAME", ""), "Photo");
		Drawable drawable = new BitmapDrawable(photo);

		view4_user_image_my.setImageDrawable(drawable);

		view4_user_name_my = (TextView) view4.findViewById(R.id.user_name_my);
		view4_user_name_my.setText(sp_userMessage.getString("USER_NAME", ""));

		view4_linearLayout = (LinearLayout) view4
				.findViewById(R.id.user_linearLayout);
		view4_linearLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(MainActivity.this,
						UserInformationActivity.class);
				startActivityForResult(intent, REQUEST_CODE);
				// startActivity(intent);

			}
		});

		exit_account_button = (Button) view4
				.findViewById(R.id.exit_account_button);
		exit_account_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), LoginActivity.class);
				intent.putExtra("exit_login", 0);
				startActivity(intent);

				finish();

			}
		});

		about_us_button = (Button) view4.findViewById(R.id.about_us);
		about_us_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), AboutActivity.class);
				startActivity(intent);

			}
		});

	}

	public class MyViewPagerAdapter extends PagerAdapter {
		private List<View> mListViews;

		public MyViewPagerAdapter(List<View> mListViews) {
			super();
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(mListViews.get(position));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mListViews.get(position), 0);
			return mListViews.get(position);
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}

	private class TabClickListener implements View.OnClickListener {

		private int index = 0;

		public TabClickListener(int index) {
			super();
			this.index = index;
		}

		@Override
		public void onClick(View view) {

			mViewPager.setCurrentItem(index);

		}

	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int arg0) {

		}

		public MyOnPageChangeListener() {
			super();
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		public void onPageSelected(int arg0) {

			switch (arg0) {
			case 0:

				menu_action_intimacy.setImageResource(R.drawable.menu_chat1);
				txt_intimacy.setTextColor(Color.rgb(233, 19, 19));
				menu_action_addressBook
						.setImageResource(R.drawable.menu_contacts0);
				txt_addressBook.setTextColor(Color.rgb(17, 17, 17));
				menu_action_findFriends
						.setImageResource(R.drawable.menu_descover0);
				txt_findFriends.setTextColor(Color.rgb(17, 17, 17));
				menu_action_myInfromation.setImageResource(R.drawable.menu_me0);
				txt_myInfromation.setTextColor(Color.rgb(17, 17, 17));

				break;
			case 1:

				menu_action_intimacy.setImageResource(R.drawable.menu_chat0);
				txt_intimacy.setTextColor(Color.rgb(17, 17, 17));
				menu_action_addressBook
						.setImageResource(R.drawable.menu_contacts1);
				txt_addressBook.setTextColor(Color.rgb(233, 19, 19));
				menu_action_findFriends
						.setImageResource(R.drawable.menu_descover0);
				txt_findFriends.setTextColor(Color.rgb(17, 17, 17));
				menu_action_myInfromation.setImageResource(R.drawable.menu_me0);
				txt_myInfromation.setTextColor(Color.rgb(17, 17, 17));

				break;
			case 2:

				menu_action_intimacy.setImageResource(R.drawable.menu_chat0);
				txt_intimacy.setTextColor(Color.rgb(17, 17, 17));
				menu_action_addressBook
						.setImageResource(R.drawable.menu_contacts0);
				txt_addressBook.setTextColor(Color.rgb(17, 17, 17));
				menu_action_findFriends
						.setImageResource(R.drawable.menu_descover1);
				txt_findFriends.setTextColor(Color.rgb(233, 19, 19));
				menu_action_myInfromation.setImageResource(R.drawable.menu_me0);
				txt_myInfromation.setTextColor(Color.rgb(17, 17, 17));

				break;

			case 3:

				menu_action_intimacy.setImageResource(R.drawable.menu_chat0);
				txt_intimacy.setTextColor(Color.rgb(17, 17, 17));
				menu_action_addressBook
						.setImageResource(R.drawable.menu_contacts0);
				txt_addressBook.setTextColor(Color.rgb(17, 17, 17));
				menu_action_findFriends
						.setImageResource(R.drawable.menu_descover0);
				txt_findFriends.setTextColor(Color.rgb(17, 17, 17));
				menu_action_myInfromation.setImageResource(R.drawable.menu_me1);
				txt_myInfromation.setTextColor(Color.rgb(233, 19, 19));

				break;

			}
		}
	}

	/**
	 * 初始化好友列表信息
	 */
	private void initFriendsList() {

		try {

			int i;

			FriendInformation friendInformation;

			JSONArray jsonArray = new JSONArray(CacheUtil.getFromFile(
					"friendsInformation", "Friend"));

			for (i = 0; i < jsonArray.length(); i++) {

				JSONObject jsonObject = (JSONObject) jsonArray.get(i);

				friendInformation = new FriendInformation();

				friendInformation.setUsername(jsonObject.optString("username"));
				friendInformation.setPortrait(jsonObject.optString("portrait"));
				friendInformation.setSex(jsonObject.optInt("sex"));
				friendInformation.setSignature(jsonObject
						.optString("signature"));
				friendInformation.setArea(jsonObject.optString("area"));

				friendInformations.add(friendInformation);
				friendList.add(jsonObject.optString("username"));

			}

			// Log.e("friendList", friendList.toString());

		} catch (Exception e) {

			Log.e("message", e.toString());

		}

	}

	/**
	 * 双击退出软件
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:

			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 2000) {
				Toast.makeText(this, "Press again to exit the program",
						Toast.LENGTH_SHORT).show();
				firstTime = secondTime;
				return true;
			} else {
				Intent startMain = new Intent(Intent.ACTION_MAIN);
				startMain.addCategory(Intent.CATEGORY_HOME);
				startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(startMain);

				/*
				 * File file = new File(
				 * "/sdcard/Intimacy/user/Request/requestFriend.txt"); if
				 * (file.isFile()) { file.delete(); } file.exists();
				 */

				System.exit(0);
			}

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 点击按钮显示菜单
	 * 
	 * @param context
	 */
	public void uploadImage(final Activity context) {
		menuWindow = new SelectAddPopupWindow(MainActivity.this, itemsOnClick);
		// 显示窗口
		menuWindow.showAtLocation(
				MainActivity.this.findViewById(R.id.actionbar_add), Gravity.TOP
						| Gravity.RIGHT, 10, 230);// 设置layout在PopupWindow中显示的位置

	}

	/**
	 * 为弹出窗口实现监听类
	 */
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();
		}
	};

	private void getFriendRequest() {

		new Thread() {

			public void run() {

				try {

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("status", 2);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					// Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"addUser", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = null;
					result = EntityUtils.toString(httpResponse.getEntity(),
							HTTP.UTF_8);

					// Log.e("result", result + "dfgfg");

					if (!result.equals("")) {

						Log.e("result_result", result);

						JSONArray jsonArray2 = new JSONArray(result);
						JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

						if (jsonObject2.optString("status").equals("request")) {

							Message msg = new Message();
							msg.what = USER_ADD_MESSAGE;
							msg.obj = result;
							addHandler.sendMessage(msg);

						} else {

							Message msg = new Message();
							msg.what = USER_ADD_SUCCESS;
							msg.obj = jsonObject2;
							addHandler.sendMessage(msg);

						}

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	/**
	 * 将字符串转换成Bitmap图片
	 * 
	 * @param string
	 * @return
	 */
	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	public void getUserMessageAlsways() {

		new Thread() {

			public void run() {

				try {

					Log.e("asld;kakdlsjfl;asd121/////////.............",
							"asdfasdf1321314");
					ServerSocket server = null;
					server = new ServerSocket(8910);

					try {

						Socket socket = null;

						while ((socket = server.accept()) != null) {

							ReceiveThread t = new ReceiveThread(socket);
							t.start();

							while (t.isAlive())
								;

							Message msg = new Message();
							msg.what = FRIENDMESSAGE_ONTIME;
							msg.obj = socketMessage;

							friendHandler.sendMessage(msg);

							Log.e("msg.obj......", msg.obj.toString()
									+ "123456789");

							socket.close();

						}

						// socket.close();
						// server.close();

					} catch (Exception e) {
						e.printStackTrace();
					}

				} catch (IOException e1) {
					e1.printStackTrace();
				}

			}

		}.start();

	}

	/**
	 * 获取当前用户的离线消息
	 */
	private void sendSocketMessage() {

		new Thread() {

			public void run() {

				try {
					Socket socket;

					OutputStream outputStream;
					// InputStream inputStream;
					String message = null;

					socket = new Socket(IP_SOCKET, PORT_SOCKET);
					outputStream = socket.getOutputStream();
					message = getIPAdress() + " "
							+ sp_userMessage.getString("USER_NAME", "");

					Log.e("dengluxinxi.........", message);

					byte[] login = message.getBytes();
					outputStream.write(login);
					outputStream.close();

					// inputStream = socket.getInputStream();
					//
					// byte[] loginReceive = new byte[1024];
					// StringBuffer sb = new StringBuffer();
					// // String path = msg.replaceAll("\\\\","\\\\\\\\");
					// while ((inputStream.read(loginReceive)) != -1) {
					//
					// sb.append(new String(loginReceive));
					// loginReceive = new byte[1024];// 重新生成，避免和上次读取的数据重复
					// Log.e("21646546546.........", "121313216545");
					// }
					//
					// String messageReceive = new String(loginReceive);
					//
					// Log.e("messageReceive.........", messageReceive
					// + "hkqhkqhqk");
					//
					// Message msg = new Message();
					// msg.obj = messageReceive;
					// msg.what = FRIENDMESSAGE_OFFLINE;
					// friendHandler.sendMessage(msg);
					// inputStream.close();

					socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}

			}

		}.start();

	}

	/**
	 * 获取用户ip地址
	 * 
	 * @return
	 */
	public String getIPAdress() {

		WifiManager wifiManager = (WifiManager) this
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int i = wifiInfo.getIpAddress();
		return int2ip(i);
	}

	/**
	 * 转换ip显示格式
	 */
	public static String int2ip(int ipInt) {
		StringBuilder sb = new StringBuilder();
		sb.append(ipInt & 0xFF).append(".");
		sb.append((ipInt >> 8) & 0xFF).append(".");
		sb.append((ipInt >> 16) & 0xFF).append(".");
		sb.append((ipInt >> 24) & 0xFF);
		return sb.toString();
	}

	/**
	 * 将聊天记录存储到本地文件
	 * 
	 * @param jsonObject
	 */
	private void storeToFile(JSONObject jsonObject) {

		try {
			JSONArray jsonArray = null;

			if (!CacheUtil.getFromFile(
					jsonObject.optString("sendid") + "_"
							+ sp_userMessage.getString("USER_NAME", ""),
					"Send/Message").equals("")) {

				jsonArray = new JSONArray(CacheUtil.getFromFile(
						jsonObject.optString("sendid") + "_"
								+ sp_userMessage.getString("USER_NAME", ""),
						"Send/Message"));

				if (jsonObject.optInt("type") == 1) {

					jsonObject.put("flag", ListData.RECEIVER);
					jsonArray.put(jsonObject);

				} else if (jsonObject.optInt("type") == 2) {

					Bitmap bitmap = stringtoBitmap(jsonObject
							.optString("message"));
					CacheUtil.WriteToFile(jsonObject.optString("receiveid")
							+ jsonObject.optString("sendid")
							+ timeChange(jsonObject.optString("time")), bitmap,
							"Send" + "/" + "Photo");

					JSONObject jsonObject_new = new JSONObject();

					jsonObject_new.put("message",
							"/sdcard/Intimacy/user/" + "Send" + "/" + "Photo"
									+ "/" + jsonObject.optString("receiveid")
									+ jsonObject.optString("sendid")
									+ timeChange(jsonObject.optString("time"))
									+ ".jpg");

					jsonObject_new
							.put("sendid", jsonObject.optString("sendid"));
					jsonObject_new.put("receiveid",
							jsonObject.optString("receiveid"));
					jsonObject_new.put("time", jsonObject.optString("time"));
					jsonObject_new.put("type", jsonObject.optInt("type"));

					jsonObject_new.put("flag", ListData.RECEIVER);
					jsonArray.put(jsonObject_new);

				} else if (jsonObject.optInt("type") == 3) {

				} else if (jsonObject.optInt("type") == 4) {

				}

			} else {

				if (jsonObject.optInt("type") == 1) {

					jsonArray = new JSONArray();
					jsonObject.put("flag", 2);
					jsonArray.put(jsonObject);

				} else if (jsonObject.optInt("type") == 2) {

					jsonArray = new JSONArray();
					JSONObject jsonObject_new = new JSONObject();

					Bitmap bitmap = stringtoBitmap(jsonObject
							.optString("message"));
					CacheUtil.WriteToFile(jsonObject.optString("receiveid")
							+ jsonObject.optString("sendid")
							+ timeChange(jsonObject.optString("time")), bitmap,
							"Send" + "/" + "Photo");

					jsonObject_new.put("message",
							"/sdcard/Intimacy/user/" + "Send" + "/" + "Photo"
									+ "/" + jsonObject.optString("receiveid")
									+ jsonObject.optString("sendid")
									+ timeChange(jsonObject.optString("time"))
									+ ".jpg");

					jsonObject_new
							.put("sendid", jsonObject.optString("sendid"));
					jsonObject_new.put("receiveid",
							jsonObject.optString("receiveid"));
					jsonObject_new.put("time", jsonObject.optString("time"));
					jsonObject_new.put("type", jsonObject.optInt("type"));

					jsonObject_new.put("flag", ListData.RECEIVER);
					jsonArray.put(jsonObject_new);

				}

			}

			CacheUtil.writeToFile(
					jsonArray.toString(),
					jsonObject.optString("sendid") + "_"
							+ sp_userMessage.getString("USER_NAME", ""),
					"Send/Message");

			JSONObject jsonObject_last = (JSONObject) jsonArray.get(jsonArray
					.length() - 1);

			if (!CacheUtil.getFromFile("UserChat", "Send/User").equals("")) {

				String usernameChat = CacheUtil.getFromFile("UserChat",
						"Send/User");

				Bitmap friendPhoto = CacheUtil.GetFromFile(
						jsonObject_last.optString("sendid"), "FriendPhoto");
				Bitmap userPhoto = CacheUtil.GetFromFile(
						jsonObject_last.optString("receiveid"), "Photo");

				if (jsonObject.optString("sendid").equals(usernameChat)) {

					ChatActivity.updateMessage(
							jsonObject_last.optString("sendid"),
							jsonObject_last.optString("receiveid"),
							jsonObject_last.optString("message"),
							jsonObject_last.optInt("flag"),
							jsonObject_last.optString("time"), friendPhoto,
							userPhoto, jsonObject_last.optInt("type"));

				}

			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 时间转换
	 * 
	 * @param currentTime
	 * @return
	 */
	private String getTime(double currentTime) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		Date curDate = new Date();
		String str = format.format(curDate);
		return str;

	}

	public static void getMessage(String str) {

		socketMessage = str;
		Log.e("socketMessage", socketMessage);

	}

	public long timeChange(String str) {

		long millionSeconds = 0;

		try {

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

			millionSeconds = sdf.parse(str).getTime();// 毫秒

			return millionSeconds;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return millionSeconds;

	}
}
